# 定义源目录和目标目录
$sourceDir = "D:\\" # 根据需要修改为搜索的根目录，默认为C盘根目录
$targetBaseDir = "E:\OrganizedFiles" # E盘下的目标文件夹路径

# 创建目标文件夹
$extensions = @(".rar", ".docx", ".pdf", ".xlsx")
foreach ($ext in $extensions) {
    $targetDir = Join-Path -Path $targetBaseDir -ChildPath $ext.TrimStart('.')
    if (-not (Test-Path -Path $targetDir)) {
        New-Item -ItemType Directory -Path $targetDir | Out-Null
    }
}

# 遍历所有文件并移动到对应的目标文件夹
foreach ($ext in $extensions) {
    $files = Get-ChildItem -Path $sourceDir -Filter *$ext -Recurse -ErrorAction SilentlyContinue
    foreach ($file in $files) {
        try {
            Write-Host "hello"
            $targetDir = Join-Path -Path $targetBaseDir -ChildPath $ext.TrimStart('.')
            Move-Item -Path $file.FullName -Destination $targetDir -Force -ErrorAction Stop
            Write-Host "Moved $($file.FullName) to $targetDir"
        } catch {
            Write-Warning "Failed to move $($file.FullName): $_"
        }
    }
}